<?php
/**
 * Created by PhpStorm.
 * User: LENOVO
 * Date: 2019/3/28
 * Time: 16:26
 */

namespace app\admin\controller;


use common\Ret;
use controller\AuthBasic;
use service\QueryService;
use think\Db;
use think\Exception;
use think\Log;

class Dictionary extends AuthBasic{

    public $table = "SysDictionary";
    public $title = "字典管理";
    protected function _index_where_filter(&$query,  $where){
        $filter = [
            "like" => ['name', 'key', 'remark']
        ];
        QueryService::decorateQuery($query, $where, $filter);
    }
    public function index() {
        $query = Db::name($this->table);
        return $this->_list($query, input(''));
    }
    protected function dictionary_form() {

        // 非POST请求, 获取数据并显示表单页面
        if (!$this->request->isPost()) {
            $id = input('id','');
            if(!empty($id)) {
                $dictionary = Db::name($this->table)->where('id', $id)->find();
                $dictionary_set = Db::name("SysDictionarySet")->where("dict", $dictionary['key'])->select();
                $this->assign("vo", $dictionary);
                $this->assign("set", $dictionary_set);
            }
            return $this->fetch('form');
        }
        $id = input('id', "");
        $dictionary = [
          "name"    => input('name', ''),
          "key"     => input('key', ''),
          "desc"    => input('desc', "")
        ];
        $set = input('set/a', []);
        $dictionary_set = [];
        foreach($set as $_) {
            $_['dict'] = $dictionary['key'];
            array_push($dictionary_set, $_);
        }
        if(!empty($id)) {//编辑
            $validate_res = $this->validate("Dictionary", $dictionary);
            if(true !== $validate_res) {
                return $this->ret->setCode(Ret::$_RET_ERROR)->setMsg($validate_res)->toJson();
            }else {
                Db::startTrans();
                try{
                    Log::write("ID:{$id}");
                    $last = Db::name($this->table)->where("id", $id)->find();
                    Db::name("SysDictionarySet")->where("dict", $last['key'])->delete();
                    Db::name($this->table)->where("id", $id)->update($dictionary);
                    Db::name("SysDictionarySet")->insertAll($dictionary_set);
                    Db::commit();
                    return $this->ret->setCode(Ret::$_RET_RELOAD)->setMsg('数据保存成功')->toJson();
                }catch(Exception $e) {
                    Db::rollback();
                    return $this->ret->setCode(Ret::$_RET_ERROR)->setMsg('数据保存失败，请重试')->toJson();
                }
            }
        }else {
            $validate = validate('Dictionary');
            $validate_res = $validate->scene("add")->check($dictionary);
            if(true !== $validate_res) {
                return $this->ret->setCode(Ret::$_RET_ERROR)->setMsg($validate_res)->toJson();
            }else {
                Db::startTrans();
                try{
                    Db::name($this->table)->insert($dictionary);
                    Db::name("SysDictionarySet")->insertAll($dictionary_set);
                    Db::commit();
                    return $this->ret->setCode(Ret::$_RET_RELOAD)->setMsg('数据保存成功')->toJson();
                }catch(Exception $e) {
                    Db::rollback();
                    return $this->ret->setCode(Ret::$_RET_ERROR)->setMsg('数据保存失败，请重试')->toJson();
                }
            }
        }

    }

    public function add() {
        return $this->dictionary_form();
    }

    public function edit() {
        return $this->dictionary_form();
    }

    public function del() {
        $id = input('id', '');
        Db::startTrans();
        try{
            $dictionary = Db::name("SysDictionary")->where("id", $id)->find();
            if($dictionary) {
                Db::name("SysDictionarySet")->where("dict", $dictionary['key'])->delete();
                Db::name("SysDictionary")->where("id", $id)->delete();
                Db::commit();
                return $this->ret->setCode(Ret::$_RET_RELOAD)->setMsg("删除成功")->toJson();
            }
            return $this->ret->setCode(Ret::$_RET_ERROR)->setMsg("未找到该字典记录，请重试")->toJson();
        }catch (Exception $e) {
            Db::rollback();
            return $this->ret->setCode(Ret::$_RET_ERROR)->setMsg("删除数据失败，请重试")->toJson();
        }
    }
}